package com.api.shopapi.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.MedicinerDTO;
import com.api.shopapi.entity.dto.MedicinerStaffRelDTO;
import com.api.shopapi.entity.template.ExportMediciner;
import com.api.shopapi.service.InstitutionService;
import com.api.shopapi.service.MedicinerService;
import com.api.shopapi.service.StaffService;
import com.api.shopapi.service.UserService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("ExportMediciner")
public class ExportMedicinerController extends BaseController{


    @Value("${my.templates.exportMediciner}")
    protected String templatesExportMediciner;


    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;


    @Autowired
    @Qualifier("MedicinerServiceImplOne")
    private MedicinerService medicinerService;


    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    @Autowired
    @Qualifier("InstitutionServiceImplOne")
    private InstitutionService institutionService;



    @RequestMapping(value = "GovExport", method = RequestMethod.GET)
    @ResponseBody
    public MyResult GovExport(@RequestParam("timeStr") String timeStr,
                              @RequestParam("sign") String sign,
                              @RequestParam("staffCode") String staffCode,
                              @RequestParam("institutionCode") String institutionCode,
                              HttpServletResponse response) {
        try {

            int pageIndex = 1;
            int pageSize = 999999;

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Mediciner/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            Institution institution = institutionService.getByInstitutionCode(institutionCode);
            User user2 = userService.getByUserCode(institution.getUserCode());

            PageInfo<Mediciner> pageInfo = medicinerService.pageByGovCodeInsCode(pageIndex,pageSize,
                    staff.getGovernmentCode(),institutionCode);

            List<ExportMediciner> listDTO = new ArrayList<>();
            for(Mediciner mediciner:pageInfo.getList()){

                mediciner = medicinerService.getByMedicinerCode(mediciner.getMedicinerCode());
                User user = userService.getByUserCode(mediciner.getUserCode());

                ExportMediciner exportMediciner = new ExportMediciner();
                exportMediciner.setUserName(user.getName());
                exportMediciner.setIdCard(mediciner.getIdCard());
                exportMediciner.setAddress(mediciner.getAddress());
                exportMediciner.setInstitutionName(user2.getName());

                listDTO.add(exportMediciner);

            }



            ClassPathResource classPathResource = new ClassPathResource(templatesExportMediciner);
            InputStream inputStream = classPathResource.getInputStream();
            File somethingFile = File.createTempFile("test", ".xlsx");
            FileUtils.copyInputStreamToFile(inputStream, somethingFile);
            String templateFileName = somethingFile.getAbsolutePath();

            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("医生列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), ExportMediciner.class)
                    .withTemplate(templateFileName).sheet()
                    .doWrite(listDTO);


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);
            return success(jsonObject1);
        }  catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }



}
